package at.gv.bmwf.fons.model.ontology;

import java.util.Set;

import at.gv.bmwf.fons.model.ontology.uris.VONT;

import com.google.common.collect.Sets;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.sparql.engine.binding.Binding;
import com.hp.hpl.jena.vocabulary.RDFS;

public class AtomFactory {
	private final OntModel viewModel;
	
	public AtomFactory (OntModel viewModel) {
		this.viewModel = viewModel;
	}
	
	public Set<Atom> load(Selection sel) {
		Resource selection = sel.getResource();
		final Set<Atom> atoms = Sets.newHashSet();
		
		final String queryString = "SELECT DISTINCT ?facet ?facetCategory ?facetStructure ?atom WHERE { " +
				"<" + selection + "> <" + VONT.selectsAtom + "> ?atom." +
				"?atom <" + VONT.hasFacet + "> ?facet." +
				"?facet a ?facetCategory." + 
				"?facet a ?facetStructure." + 
				"?facetCategory <" + RDFS.subClassOf + "> <" + VONT.prefix + "CategorialFacet>." +
				//"?facetCategory a <" + VONT.prefix + "ViewClass>." +
				"?facetStructure <" + RDFS.subClassOf + "> <" + VONT.prefix + "StructuralFacet>." +
				"?facetStructure a <" + VONT.prefix + "ViewClass>." +
				"} GROUP BY ?atom ?facet ?facetCategory ?facetStructure ORDER BY ?atom ?facet";
		
		StringBuilder builder = new StringBuilder();
		ResultSet result = QueryExecutionFactory.create(QueryFactory.create(queryString), viewModel).execSelect();
				
		while (result.hasNext()) {
			QuerySolution solution = result.next();
			
			builder.append(solution.get("?atom") + " -- " + solution.get("?facet") + ": " + solution.get("?facetCategory")
					+ ", a "+ solution.get("?facetStructure") + "\n");
			/*for (Statement stmt: solution.get("?atom").asResource().listProperties(VONT.hasFacet).toList()) {
				builder.append("\t" + stmt.getObject().asResource().listProperties() + "\n");	
			}*/
		}
		
		System.out.println("Atoms with facets:\n" + builder);
				
		return atoms;
	}	
}
